package fr.alesia.deepstack.stat.simple;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import fr.alesia.deepstack.bean.Player;
import fr.alesia.deepstack.bean.Ranking;
import fr.alesia.deepstack.bean.Tournament;
import fr.alesia.deepstack.data.PlayerDao;
import fr.alesia.deepstack.data.RankingDao;
import fr.alesia.deepstack.data.TournamentDao;
import fr.alesia.deepstack.factory.DaoFactory;
import fr.alesia.deepstack.factory.ServiceFactory;
import fr.alesia.deepstack.stat.GeneralStatistics;

public class GeneralStatisticsSimple implements GeneralStatistics {

	private static GeneralStatistics instance = null;
	private static TournamentDao daoTournaments;
	private static PlayerDao daoPlayers;
	private static RankingDao daoRankings;
	
	private GeneralStatisticsSimple(){
		
		daoTournaments = DaoFactory.getTournamentDao();
		daoPlayers = DaoFactory.getPlayerDao();
		daoRankings = DaoFactory.getRankingDao();
	}
	
	public static GeneralStatistics getInstance(){
		if(instance == null){
			instance = new GeneralStatisticsSimple();
		}
		return instance;
	}
	
	public Float getAverageNumberOfPlayers() {
		
		Set<Tournament> tournaments = daoTournaments.findAll();
		int t = tournaments.size();
		int p = 0;
		for (Tournament tournament : tournaments) {
			p = p + ServiceFactory.getTournamentService(tournament).getNbPlayers();
		}
		tournaments = null;
		return (t == 0 ? null : (float)p/(float)t);
	}

	public SortedMap<Player, Integer> getHallOfFame() {
		
		
		Set<Player> players = daoPlayers.findAll();
		Map<Player, Integer> scores = new HashMap<Player, Integer>(players.size());
		
		for (Player player : players) {
			Set<Ranking> rankings = daoRankings.findByPlayer(player);
			int points = 0;
			for (Ranking ranking : rankings) {
				points = points + ranking.getPoints();
			}
			scores.put(player, points);
			rankings = null;
		}
		
		SortedMap<Player, Integer> hallOfFame =
			new TreeMap<Player, Integer>(new PlayerComparator(scores));
			
		for (Player player : scores.keySet()) {		
			hallOfFame.put(player, scores.get(player));
		}
		
		scores = null;
		players = null;
		
		return hallOfFame;
	}

	public Integer getNumberOfPlayers() {
		return daoPlayers.findAll().size();
	}

	public Integer getNumberOfTournaments() {
		return daoTournaments.findAll().size();
	}
}
